// pages/consumCenter/index.js
const moment = require('moment')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        shopPopup: false,
        couponList: [],
        isCollect: false,
        popupText: '',
        is_get: 0,
        coupon_id: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getcouponlist()
    },
    /**
     * 消费卷列表
     */
    getcouponlist() {
        wx.http.get(wx.api.getcouponlist, {
            page: 1
        }).then(res => {
            const list = res.data.data.map(t => ({
                ...t,
                discount: Number(t.discount),
                use_stime: moment(t.use_stime * 1000).format('YYYY年MM月DD日'),
                use_etime: moment(t.use_etime * 1000).format('MM月DD日')
            }))
            if (res.code == 1) {
                this.setData({
                    couponList: list
                })
            }
        })
    },
    /**
     * 确定领取
     */
    onCancelConfim() {
        let {
            coupon_id,
            is_get,
            popupText,
            couponList
        } = this.data
        wx.http.post(wx.api.usergetcoupon, {
            coupon_id
        }).then(res => {
            if (res.code == 1) {
                couponList = couponList.map(t => ({
                    ...t,
                    is_get: t.coupon_id == coupon_id && 1
                }))
                popupText = '您已成功领取优惠卷'
            } else {
                popupText = '领取失败'
            }
            this.setData({
                is_get: 1,
                popupText,
                couponList
            })
        })
    },
    /**
     * 领取弹窗
     */
    onShowCollect(e) {
        let {
            id
        } = e.currentTarget.dataset
        let {
            coupon_id,
            is_get,
            popupText
        } = this.data
        let data = this.data.couponList.find(item => item.coupon_id == id)
        coupon_id = data.coupon_id
        is_get = data.is_get
        popupText = is_get == 1 ? '你已领取过优惠卷\n无法重新领取哦~' : '是否确认要领券？'
        this.setData({
            shopPopup: true,
            popupText,
            is_get,
            coupon_id
        })
    },
    /**
     * 取消领取
     */
    onCancelCollect() {
        this.setData({
            shopPopup: false
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})